package com.example.shopping.controller;

import com.example.shopping.entity.Goods;
import com.example.shopping.entity.GoodsType;
import com.example.shopping.service.GoodsService;
import com.example.shopping.service.GoodsTypeService;
import com.example.shopping.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsTypeService goodsTypeService;


    // 查询所有商品并展示列表
    @GetMapping("/list")
    public String listGoods(Model model) {
        List<Goods> allGoods = goodsService.findAll();
        allGoods.sort(Comparator.comparingInt(g -> Integer.parseInt(g.getGid())));
        model.addAttribute("allGoods", allGoods);
        model.addAttribute("map", goodsTypeService.findAllGoodsTypeAsMap());
        return "goodsList";
    }


    @GetMapping("/edit")
    public String showEditForm(@RequestParam("gid") String gid, Model model) {

        // 从数据库中查询商品信息
        Goods good = goodsService.findByGid(gid);


        // 将商品信息传入 Thymeleaf 页面
        model.addAttribute("good", good);


        model.addAttribute("goodstypes", goodsTypeService.findAll());


        // 返回 goodsEdit.html 页面
        return "goodsEdit";
    }


    @PostMapping("/update")
    public String updateGood(@ModelAttribute("good") Goods updatedGood) {
        goodsService.updateGood(updatedGood);


        // 重定向到商品列表页
        return "redirect:/goods/list";
    }


    @GetMapping("/delete")
    public String deleteGood(@RequestParam("gid") String gid) {
        goodsService.deleteGoodsByGid(gid); // 调用删除方法

        // 删除完成后跳转回商品列表页
        return "redirect:/goods/list";
    }


    @PostMapping("/add")
    public String addGood(@ModelAttribute("good") Goods good) {
        goodsService.addGood(good);

        return "redirect:/goods/list";
    }

    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("goodstypes", goodsTypeService.findAll());
        return "goodsAdd";
    }
}
